package com.sz.admin.vehicleinfo.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSON;
import com.mybatisflex.core.table.TableDef;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.sz.admin.dtuinfo.pojo.po.DtuInfo;
import com.sz.admin.system.pojo.po.SysDept;
import com.sz.admin.system.pojo.po.SysUser;
import com.sz.admin.system.service.SysUserService;
import com.sz.admin.system.service.SysUserRoleService;
import com.sz.admin.system.service.SysUserDeptService;
import com.sz.admin.system.pojo.dto.sysuser.UserDeptDTO;
import com.sz.admin.teacher.pojo.po.TeacherStatistics;
import com.sz.admin.teacher.pojo.vo.TeacherStatisticsVO;
import com.sz.core.common.entity.LoginUser;
import com.sz.core.common.exception.common.BusinessException;
import com.sz.core.datascope.SimpleDataScopeHelper;
import com.sz.core.util.*;
import com.sz.mysql.SimplePermissionDialect;
import com.sz.security.core.util.LoginUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sz.admin.vehicleinfo.service.VehicleInfoService;
import com.sz.admin.vehicleinfo.pojo.po.VehicleInfo;
import com.sz.admin.vehicleinfo.mapper.VehicleInfoMapper;
import com.sz.admin.system.mapper.SysDeptMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.query.QueryChain;
import com.sz.core.common.enums.CommonResponseEnum;
import com.sz.core.common.entity.PageResult;
import com.sz.core.common.entity.SelectIdsDTO;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.Objects;
import java.util.stream.Collectors;
import com.sz.admin.vehicleinfo.pojo.dto.VehicleInfoCreateDTO;
import com.sz.admin.vehicleinfo.pojo.dto.VehicleInfoUpdateDTO;
import com.sz.admin.vehicleinfo.pojo.dto.VehicleInfoListDTO;
import com.sz.admin.vehicleinfo.pojo.dto.VehicleInfoImportDTO;
import com.sz.core.common.entity.ImportExcelDTO;
import com.sz.excel.core.ExcelResult;
import java.io.OutputStream;
import jakarta.servlet.http.HttpServletResponse;
import com.sz.excel.utils.ExcelUtils;
import lombok.SneakyThrows;
import com.sz.admin.vehicleinfo.pojo.vo.VehicleInfoVO;
import org.springframework.transaction.annotation.Transactional;

import static com.sz.admin.system.pojo.po.table.SysDeptTableDef.SYS_DEPT;
import static com.sz.admin.system.pojo.po.table.SysUserTableDef.SYS_USER;
import static com.sz.admin.vehicleinfo.pojo.po.table.VehicleInfoTableDef.VEHICLE_INFO;
import static com.mybatisflex.core.query.QueryMethods.*;
import static com.sz.admin.vehicleschedule.pojo.po.table.VehicleScheduleTableDef.VEHICLE_SCHEDULE;
import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * <p>
 * 车辆管理 服务实现类
 * </p>
 *
 * @author sz-admin
 * @since 2025-08-29
 */
@Service
@RequiredArgsConstructor
public class VehicleInfoServiceImpl extends ServiceImpl<VehicleInfoMapper, VehicleInfo> implements VehicleInfoService {

    @Autowired
    private VehicleInfoMapper vehicleInfoMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserDeptService sysUserDeptService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(VehicleInfoCreateDTO dto){
        VehicleInfo vehicleInfo = BeanCopyUtils.copy(dto, VehicleInfo.class);
        // 检查车辆编号是否已存在（未删除的）
        // 获取该部门所在树的根部门ID（pid=0）
        Long rootDeptId = findRootDepartmentId(dto.getDepartmentId());
        if (rootDeptId != null) {
            List<Long> deptIds = getSubDepartmentIds(rootDeptId);
            //
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .select()
                    .where(VEHICLE_INFO.VEHICLE_NUMBER.eq(vehicleInfo.getVehicleNumber()))
                    .and(VEHICLE_INFO.DEL_FLAG.eq("F"))
                    .and(VEHICLE_INFO.DEPARTMENT_ID.in(deptIds));;

            List<VehicleInfo> vehicleInfoList = vehicleInfoMapper.selectListByQuery(queryWrapper);
            // 判断查询结果是否不为空
            boolean exists = vehicleInfoMapper.selectCountByQuery(queryWrapper) > 0;

            if (exists) {
                // 使用 BusinessException 抛出业务异常
                throw new BusinessException(
                        CommonResponseEnum.EXISTS, // 传递一个有效的响应枚举
                        new Object[]{vehicleInfo.getVehicleNumber()}, // 参数
                        "车辆编号 " + vehicleInfo.getVehicleNumber() + " 已存在" // 消息
                );
            }
        }
        save(vehicleInfo);
        String encodePwd = getEncoderPwd(getInitPassword());
        // 处理司机账号创建逻辑
        // 1. 第一个司机
        if (dto.getDriverName() != null && !dto.getDriverName().isEmpty()) {
            String username = dto.getDriverName();
            // 检查用户名是否已存在
            QueryWrapper usernameWrapper = QueryWrapper.create()
                    .eq(SysUser::getUsername, username)
                    .eq(SysUser::getDelFlag, "F");
            CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
            
            // 校验手机号唯一性
            if (dto.getDriverPhone1() != null && !dto.getDriverPhone1().isEmpty()) {
                QueryWrapper phoneWrapper = QueryWrapper.create()
                        .eq(SysUser::getPhone, dto.getDriverPhone1())
                        .eq(SysUser::getDelFlag, "F");
                CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
            }
            
            SysUser user = new SysUser();
            user.setUsername(username);
            user.setNickname(username); // 设置昵称同用户名
            user.setPwd(encodePwd); // 默认密码：123456的MD5加密
            user.setAccountStatusCd("1000001"); // 账号状态：启用
            user.setUserTagCd("1001003"); // 用户标签：司机
            // 设置手机号
            if (dto.getDriverPhone1() != null && !dto.getDriverPhone1().isEmpty()) {
                user.setPhone(dto.getDriverPhone1());
            }
            //user.setDepartmentId(dto.getDepartmentId()); // 设置部门ID
            sysUserService.save(user);
            // 设置用户角色为司机角色 (role_id = 7)
            sysUserRoleService.syncUserRolec(user.getId(), 7L);
            
            // 设置用户部门关系
            UserDeptDTO userDeptDTO = new UserDeptDTO();
            userDeptDTO.setUserIds(List.of(user.getId()));
            userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
            sysUserDeptService.bind(userDeptDTO);
            
            vehicleInfo.setUserId1(user.getId());
        }
        
        // 2. 第二个司机
        if (dto.getDriverName2() != null && !dto.getDriverName2().isEmpty()) {
            String username = dto.getDriverName2();
            // 检查用户名是否已存在
            QueryWrapper usernameWrapper = QueryWrapper.create()
                    .eq(SysUser::getUsername, username)
                    .eq(SysUser::getDelFlag, "F");
            CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
            
            // 校验手机号唯一性
            if (dto.getDriverPhone2() != null && !dto.getDriverPhone2().isEmpty()) {
                QueryWrapper phoneWrapper = QueryWrapper.create()
                        .eq(SysUser::getPhone, dto.getDriverPhone2())
                        .eq(SysUser::getDelFlag, "F");
                CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
            }
            
            SysUser user = new SysUser();
            user.setUsername(username);
            user.setNickname(username); // 设置昵称同用户名
            user.setPwd(encodePwd); // 默认密码：123456的MD5加密
            user.setAccountStatusCd("1000001"); // 账号状态：启用
            user.setUserTagCd("1001003"); // 用户标签：司机
            // 设置手机号
            if (dto.getDriverPhone2() != null && !dto.getDriverPhone2().isEmpty()) {
                user.setPhone(dto.getDriverPhone2());
            }
            //user.setDepartmentId(dto.getDepartmentId()); // 设置部门ID
            sysUserService.save(user);
            // 设置用户角色为司机角色 (role_id = 7)
            sysUserRoleService.syncUserRolec(user.getId(), 7L);
            
            // 设置用户部门关系
            UserDeptDTO userDeptDTO = new UserDeptDTO();
            userDeptDTO.setUserIds(List.of(user.getId()));
            userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
            sysUserDeptService.bind(userDeptDTO);
            
            vehicleInfo.setUserId2(user.getId());
        }
        
        // 3. 第三个司机
        if (dto.getDriverName3() != null && !dto.getDriverName3().isEmpty()) {
            String username = dto.getDriverName3();
            // 检查用户名是否已存在
            QueryWrapper usernameWrapper = QueryWrapper.create()
                    .eq(SysUser::getUsername, username)
                    .eq(SysUser::getDelFlag, "F");
            CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
            
            // 校验手机号唯一性
            if (dto.getDriverPhone3() != null && !dto.getDriverPhone3().isEmpty()) {
                QueryWrapper phoneWrapper = QueryWrapper.create()
                        .eq(SysUser::getPhone, dto.getDriverPhone3())
                        .eq(SysUser::getDelFlag, "F");
                CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
            }
            
            SysUser user = new SysUser();
            user.setUsername(username);
            user.setNickname(username); // 设置昵称同用户名
            user.setPwd(encodePwd); // 默认密码：123456的MD5加密
            user.setAccountStatusCd("1000001"); // 账号状态：启用
            user.setUserTagCd("1001003"); // 用户标签：司机
            // 设置手机号
            if (dto.getDriverPhone3() != null && !dto.getDriverPhone3().isEmpty()) {
                user.setPhone(dto.getDriverPhone3());
            }
            //user.setDepartmentId(dto.getDepartmentId()); // 设置部门ID
            sysUserService.save(user);
            // 设置用户角色为司机角色 (role_id = 7)
            sysUserRoleService.syncUserRolec(user.getId(), 7L);
            
            // 设置用户部门关系
            UserDeptDTO userDeptDTO = new UserDeptDTO();
            userDeptDTO.setUserIds(List.of(user.getId()));
            userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
            sysUserDeptService.bind(userDeptDTO);
            
            vehicleInfo.setUserId3(user.getId());
        }
        
        // 更新车辆信息，保存司机ID
        updateById(vehicleInfo);
    }
    private String getEncoderPwd(String pwd) {
        return BCrypt.hashpw(pwd, BCrypt.gensalt(10));
    }
    private String getInitPassword() {
        return SysConfigUtils.getConfValue("sys.user.initPwd");
    }
    /**
     * 查找部门的根部门ID（pid=0）
     */
    private Long findRootDepartmentId(Long deptId) {
        SysDept dept = sysDeptMapper.selectOneById(deptId);
        if (dept == null) {
            return null;
        }

        if (dept.getPid() == 0) {
            return dept.getId();
        }

        return findRootDepartmentId(dept.getPid());
    }
    /**
     * 递归获取所有子部门ID
     */
    private List<Long> getSubDepartmentIds(Long deptId) {
        List<Long> result = new ArrayList<>();
        result.add(deptId);

        // 查询直接子部门
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(SYS_DEPT.ID)
                .where(SYS_DEPT.PID.eq(deptId))
                .and(SYS_DEPT.DEL_FLAG.eq("F"));

        List<SysDept> subDepts = sysDeptMapper.selectListByQuery(queryWrapper);

        for (SysDept dept : subDepts) {
            result.addAll(getSubDepartmentIds(dept.getId()));
        }

        return result;
    }
    
    /**
     * 递归查找子部门
     * 
     * @param parentDeptIds 父部门ID列表
     * @param result 结果集合
     */
    private void findChildDepartments(List<Long> parentDeptIds, Set<Long> result) {
        if (parentDeptIds.isEmpty()) {
            return;
        }
        
        // 查询父部门的直接子部门
        QueryWrapper childQuery = QueryWrapper.create()
                .select(SYS_DEPT.ID)
                .from(SYS_DEPT)
                .where(SYS_DEPT.PID.in(parentDeptIds))
                .and(SYS_DEPT.DEL_FLAG.eq("F"));
        
        List<SysDept> childDepts = sysDeptMapper.selectListByQuery(childQuery);
        if (childDepts.isEmpty()) {
            return;
        }
        
        // 提取子部门ID
        List<Long> childDeptIds = childDepts.stream()
                .map(SysDept::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        
        // 添加到结果中
        result.addAll(childDeptIds);
        
        // 递归查找子部门的子部门
        findChildDepartments(childDeptIds, result);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(VehicleInfoUpdateDTO dto){
        VehicleInfo vehicleInfo = BeanCopyUtils.copy(dto, VehicleInfo.class);
        QueryWrapper wrapper;
        // id有效性校验
        wrapper = QueryWrapper.create()
            .eq(VehicleInfo::getId, dto.getId());
        CommonResponseEnum.INVALID_ID.assertTrue(count(wrapper) <= 0);

        // 先查询原车辆信息，获取司机用户ID
        VehicleInfo originalVehicleInfo = getById(dto.getId());
        if (originalVehicleInfo != null) {
            // 1. 处理第一个司机
            if (dto.getDriverName() != null && !dto.getDriverName().isEmpty()) {
                if (originalVehicleInfo.getUserId1() != null) {
                    // 编辑现有司机
                    SysUser user = sysUserService.getById(originalVehicleInfo.getUserId1());
                    if (user != null && !dto.getDriverName().equals(user.getUsername())) {
                        // 校验用户名唯一性
                        QueryWrapper usernameWrapper = QueryWrapper.create()
                                .eq(SysUser::getUsername, dto.getDriverName())
                                .ne(SysUser::getId, originalVehicleInfo.getUserId1())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
                        
                        user.setUsername(dto.getDriverName());
                        user.setNickname(dto.getDriverName());
                    }
                    // 设置手机号为传递来的值（无论用户名是否改变都要检查手机号）
                    if (dto.getDriverPhone1() != null && !dto.getDriverPhone1().isEmpty()) {
                        // 校验手机号唯一性
                        QueryWrapper phoneWrapper = QueryWrapper.create()
                                .eq(SysUser::getPhone, dto.getDriverPhone1())
                                .ne(SysUser::getId, originalVehicleInfo.getUserId1())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
                        user.setPhone(dto.getDriverPhone1());
                    }
                    if (user != null) {
                        sysUserService.updateById(user);
                        // 确保用户角色为司机角色 (role_id = 7)
                        sysUserRoleService.syncUserRolec(user.getId(), 7L);
                        
                        // 更新用户部门关系
                        UserDeptDTO userDeptDTO = new UserDeptDTO();
                        userDeptDTO.setUserIds(List.of(user.getId()));
                        userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
                        sysUserDeptService.bind(userDeptDTO);
                    }
                } else {
                    // 创建新司机
                    String encodePwd = getEncoderPwd(getInitPassword());
                    // 检查用户名是否已存在
                    QueryWrapper usernameWrapper = QueryWrapper.create()
                            .eq(SysUser::getUsername, dto.getDriverName())
                            .eq(SysUser::getDelFlag, "F");
                    CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
                    
                    // 校验手机号唯一性
                    if (dto.getDriverPhone1() != null && !dto.getDriverPhone1().isEmpty()) {
                        QueryWrapper phoneWrapper = QueryWrapper.create()
                                .eq(SysUser::getPhone, dto.getDriverPhone1())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
                    }
                    
                    SysUser user = new SysUser();
                    user.setUsername(dto.getDriverName());
                    user.setNickname(dto.getDriverName()); // 设置昵称同用户名
                    user.setPwd(encodePwd); // 默认密码
                    user.setAccountStatusCd("1000001"); // 账号状态：启用
                    user.setUserTagCd("1001003"); // 用户标签：司机
                    // 设置手机号
                    if (dto.getDriverPhone1() != null && !dto.getDriverPhone1().isEmpty()) {
                        user.setPhone(dto.getDriverPhone1());
                    }
                    sysUserService.save(user);
                    // 设置用户角色为司机角色 (role_id = 7)
                    sysUserRoleService.syncUserRolec(user.getId(), 7L);
                    
                    // 设置用户部门关系
                    UserDeptDTO userDeptDTO = new UserDeptDTO();
                    userDeptDTO.setUserIds(List.of(user.getId()));
                    userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
                    sysUserDeptService.bind(userDeptDTO);
                    
                    vehicleInfo.setUserId1(user.getId());
                }
            } else if (originalVehicleInfo.getUserId1() != null) {
                // 如果司机姓名为空但原来有司机，则清除司机信息
                vehicleInfo.setUserId1(null);
            }
            
            // 2. 处理第二个司机
            if (dto.getDriverName2() != null && !dto.getDriverName2().isEmpty()) {
                if (originalVehicleInfo.getUserId2() != null) {
                    // 编辑现有司机
                    SysUser user = sysUserService.getById(originalVehicleInfo.getUserId2());
                    if (user != null && !dto.getDriverName2().equals(user.getUsername())) {
                        // 校验用户名唯一性
                        QueryWrapper usernameWrapper = QueryWrapper.create()
                                .eq(SysUser::getUsername, dto.getDriverName2())
                                .ne(SysUser::getId, originalVehicleInfo.getUserId2())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
                        
                        user.setUsername(dto.getDriverName2());
                        user.setNickname(dto.getDriverName2());
                    }
                    // 设置手机号为传递来的值（无论用户名是否改变都要检查手机号）
                    if (dto.getDriverPhone2() != null && !dto.getDriverPhone2().isEmpty()) {
                        // 校验手机号唯一性
                        QueryWrapper phoneWrapper = QueryWrapper.create()
                                .eq(SysUser::getPhone, dto.getDriverPhone2())
                                .ne(SysUser::getId, originalVehicleInfo.getUserId2())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
                        user.setPhone(dto.getDriverPhone2());
                    }
                    if (user != null) {
                        sysUserService.updateById(user);
                        // 确保用户角色为司机角色 (role_id = 7)
                        sysUserRoleService.syncUserRolec(user.getId(), 7L);
                        
                        // 更新用户部门关系
                        UserDeptDTO userDeptDTO = new UserDeptDTO();
                        userDeptDTO.setUserIds(List.of(user.getId()));
                        userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
                        sysUserDeptService.bind(userDeptDTO);
                    }
                } else {
                    // 创建新司机
                    String encodePwd = getEncoderPwd(getInitPassword());
                    // 检查用户名是否已存在
                    QueryWrapper usernameWrapper = QueryWrapper.create()
                            .eq(SysUser::getUsername, dto.getDriverName2())
                            .eq(SysUser::getDelFlag, "F");
                    CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
                    
                    // 校验手机号唯一性
                    if (dto.getDriverPhone2() != null && !dto.getDriverPhone2().isEmpty()) {
                        QueryWrapper phoneWrapper = QueryWrapper.create()
                                .eq(SysUser::getPhone, dto.getDriverPhone2())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
                    }
                    
                    SysUser user = new SysUser();
                    user.setUsername(dto.getDriverName2());
                    user.setNickname(dto.getDriverName2()); // 设置昵称同用户名
                    user.setPwd(encodePwd); // 默认密码
                    user.setAccountStatusCd("1000001"); // 账号状态：启用
                    user.setUserTagCd("1001003"); // 用户标签：司机
                    // 设置手机号
                    if (dto.getDriverPhone2() != null && !dto.getDriverPhone2().isEmpty()) {
                        user.setPhone(dto.getDriverPhone2());
                    }
                    sysUserService.save(user);
                    // 设置用户角色为司机角色 (role_id = 7)
                    sysUserRoleService.syncUserRolec(user.getId(), 7L);
                    
                    // 设置用户部门关系
                    UserDeptDTO userDeptDTO = new UserDeptDTO();
                    userDeptDTO.setUserIds(List.of(user.getId()));
                    userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
                    sysUserDeptService.bind(userDeptDTO);
                    
                    vehicleInfo.setUserId2(user.getId());
                }
            } else if (originalVehicleInfo.getUserId2() != null) {
                // 如果司机姓名为空但原来有司机，则清除司机信息
                vehicleInfo.setUserId2(null);
            }
            
            // 3. 处理第三个司机
            if (dto.getDriverName3() != null && !dto.getDriverName3().isEmpty()) {
                if (originalVehicleInfo.getUserId3() != null) {
                    // 编辑现有司机
                    SysUser user = sysUserService.getById(originalVehicleInfo.getUserId3());
                    if (user != null && !dto.getDriverName3().equals(user.getUsername())) {
                        // 校验用户名唯一性
                        QueryWrapper usernameWrapper = QueryWrapper.create()
                                .eq(SysUser::getUsername, dto.getDriverName3())
                                .ne(SysUser::getId, originalVehicleInfo.getUserId3())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
                        
                        user.setUsername(dto.getDriverName3());
                        user.setNickname(dto.getDriverName3());
                    }
                    // 设置手机号为传递来的值（无论用户名是否改变都要检查手机号）
                    if (dto.getDriverPhone3() != null && !dto.getDriverPhone3().isEmpty()) {
                        // 校验手机号唯一性
                        QueryWrapper phoneWrapper = QueryWrapper.create()
                                .eq(SysUser::getPhone, dto.getDriverPhone3())
                                .ne(SysUser::getId, originalVehicleInfo.getUserId3())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
                        user.setPhone(dto.getDriverPhone3());
                    }
                    if (user != null) {
                        sysUserService.updateById(user);
                        // 确保用户角色为司机角色 (role_id = 7)
                        sysUserRoleService.syncUserRolec(user.getId(), 7L);
                        
                        // 更新用户部门关系
                        UserDeptDTO userDeptDTO = new UserDeptDTO();
                        userDeptDTO.setUserIds(List.of(user.getId()));
                        userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
                        sysUserDeptService.bind(userDeptDTO);
                    }
                } else {
                    // 创建新司机
                    String encodePwd = getEncoderPwd(getInitPassword());
                    // 检查用户名是否已存在
                    QueryWrapper usernameWrapper = QueryWrapper.create()
                            .eq(SysUser::getUsername, dto.getDriverName3())
                            .eq(SysUser::getDelFlag, "F");
                    CommonResponseEnum.USERNAME_EXISTS.assertTrue(sysUserService.count(usernameWrapper) > 0);
                    
                    // 校验手机号唯一性
                    if (dto.getDriverPhone3() != null && !dto.getDriverPhone3().isEmpty()) {
                        QueryWrapper phoneWrapper = QueryWrapper.create()
                                .eq(SysUser::getPhone, dto.getDriverPhone3())
                                .eq(SysUser::getDelFlag, "F");
                        CommonResponseEnum.EXISTS.message("手机号已存在").assertTrue(sysUserService.count(phoneWrapper) > 0);
                    }
                    
                    SysUser user = new SysUser();
                    user.setUsername(dto.getDriverName3());
                    user.setNickname(dto.getDriverName3()); // 设置昵称同用户名
                    user.setPwd(encodePwd); // 默认密码
                    user.setAccountStatusCd("1000001"); // 账号状态：启用
                    user.setUserTagCd("1001003"); // 用户标签：司机
                    // 设置手机号
                    if (dto.getDriverPhone3() != null && !dto.getDriverPhone3().isEmpty()) {
                        user.setPhone(dto.getDriverPhone3());
                    }
                    sysUserService.save(user);
                    // 设置用户角色为司机角色 (role_id = 7)
                    sysUserRoleService.syncUserRolec(user.getId(), 7L);
                    
                    // 设置用户部门关系
                    UserDeptDTO userDeptDTO = new UserDeptDTO();
                    userDeptDTO.setUserIds(List.of(user.getId()));
                    userDeptDTO.setDeptIds(List.of(dto.getDepartmentId()));
                    sysUserDeptService.bind(userDeptDTO);
                    
                    vehicleInfo.setUserId3(user.getId());
                }
            } else if (originalVehicleInfo.getUserId3() != null) {
                // 如果司机姓名为空但原来有司机，则清除司机信息
                vehicleInfo.setUserId3(null);
            }
        }

        saveOrUpdate(vehicleInfo);
    }

    /*@Override
    public PageResult<VehicleInfoVO> page(VehicleInfoListDTO dto){
        Page<VehicleInfoVO> page = pageAs(PageUtils.getPage(dto), buildQueryWrapper(dto), VehicleInfoVO.class);
        return PageUtils.getPageResult(page);
    }*/
    @Override
    public PageResult<VehicleInfoVO> page(VehicleInfoListDTO dto){
//        try {
//            SimpleDataScopeHelper.start(VehicleInfo.class); // 指定要追加条件的表PO实体
            // 设置表别名
            SimplePermissionDialect.setTableAlias("vehicle_i");
            Page<VehicleInfoVO> page = pageAs(PageUtils.getPage(dto), buildQueryWrapper(dto), VehicleInfoVO.class);

            return PageUtils.getPageResult(page);
//        } finally {
//            SimpleDataScopeHelper.clearDataScope();
//            SimplePermissionDialect.clearTableAlias();
//        }
    }

    @Override
    public List<VehicleInfoVO> list(VehicleInfoListDTO dto){
        return listAs(buildQueryWrapper(dto), VehicleInfoVO.class);
    }


    @Override
    public void remove(SelectIdsDTO dto){
        CommonResponseEnum.INVALID_ID.assertTrue(dto.getIds().isEmpty());
        removeByIds(dto.getIds());
    }

    @Override
    public VehicleInfoVO detail(Object id){
        // 定义表别名
        TableDef parentDept = SYS_DEPT.as("parentDept");

        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(VEHICLE_INFO.ALL_COLUMNS,
                        SYS_DEPT.NAME.as("deptName"),
                        SYS_DEPT.ID.as("deptId"),
                        SYS_DEPT.PID.as("deptPid"),
                        column("parentDept.name").as("parentDeptName"),
                        column("CONCAT(IFNULL(parentDept.name, ''), ' - ', sys_d.name) as fullDeptName"),
                        column("user1.username").as("driverName"),
                        column("user1.phone").as("driverPhone1"),
                        column("user2.username").as("driverName2"),
                        column("user2.phone").as("driverPhone2"),
                        column("user3.username").as("driverName3"),
                        column("user3.phone").as("driverPhone3")
                )
                .from(VEHICLE_INFO.as("vehicle_i"))
                .leftJoin(SYS_DEPT).as("sys_d").on(SYS_DEPT.ID.eq(VEHICLE_INFO.DEPARTMENT_ID))
                .leftJoin(SYS_USER.as("user1")).on("user1.id = vehicle_i.user_id1")
                .leftJoin(SYS_USER.as("user2")).on("user2.id = vehicle_i.user_id2")
                .leftJoin(SYS_USER.as("user3")).on("user3.id = vehicle_i.user_id3")
                .leftJoin(SYS_DEPT.as("parentDept")).on("parentDept.id = sys_d.pid")
                .where(VEHICLE_INFO.ID.eq(id));

        List<VehicleInfoVO> vehicleInfoVOList = vehicleInfoMapper.selectListByQueryAs(queryWrapper, VehicleInfoVO.class);
        CommonResponseEnum.INVALID_ID.assertTrue(vehicleInfoVOList.isEmpty());
        return vehicleInfoVOList.getFirst();
    }

    @SneakyThrows
    @Override
    public void importExcel(ImportExcelDTO dto) {
        ExcelResult<VehicleInfoImportDTO> excelResult = ExcelUtils.importExcel(dto.getFile().getInputStream(), VehicleInfoImportDTO.class, true);
        List<VehicleInfoImportDTO> list = excelResult.getList();
        List<String> errorList = excelResult.getErrorList();
        String analysis = excelResult.getAnalysis();
        System.out.println(" analysis : " + analysis);
        System.out.println(" isCover : " + dto.getIsCover());
    }

    @SneakyThrows
    @Override
    public void exportExcel(VehicleInfoListDTO dto, HttpServletResponse response) {
        List<VehicleInfoVO> list = list(dto);
        String fileName = "车辆管理模板";
        OutputStream os = FileUtils.getOutputStream(response, fileName + ".xlsx");
        ExcelUtils.exportExcel(list, "车辆管理", VehicleInfoVO.class, os);
    }

    private QueryWrapper buildQueryWrapper(VehicleInfoListDTO dto) {
        Long userId = StpUtil.getLoginIdAsLong();
        LoginUser loginUser = LoginUtils.getLoginUser();
        assert loginUser != null;
        // 刷新用户信息，确保获取到最新的部门信息
        sysUserService.syncUserInfo(userId);
        // 重新获取登录用户信息，确保使用最新数据
        loginUser = LoginUtils.getLoginUser();
        assert loginUser != null;
        // 获取用户直接关联的部门ID
        List<Long> directDeptIds = loginUser.getDepts();
        
        // 递归查询这些部门及其所有子部门（基于PID关系）
        Set<Long> deptAndChildren = new HashSet<>();
        if (directDeptIds != null && !directDeptIds.isEmpty()) {
            deptAndChildren.addAll(directDeptIds);
            findChildDepartments(directDeptIds, deptAndChildren);
        }
        
        // 定义表别名
        TableDef parentDept = SYS_DEPT.as("parentDept");

        QueryWrapper wrapper = QueryWrapper.create()
                .select(VEHICLE_INFO.ALL_COLUMNS,
                        SYS_DEPT.NAME.as("deptName"),
                        SYS_DEPT.ID.as("deptId"),
                        SYS_DEPT.PID.as("deptPid"),
                        VEHICLE_SCHEDULE.TITLE.as("scheduleName"),
                        VEHICLE_SCHEDULE.SCHEDULE_TYPE.as("scheduleType"),
                        VEHICLE_SCHEDULE.TIME1.as("scheduleTime1"),
                        VEHICLE_SCHEDULE.TIME2.as("scheduleTime2"),
                        VEHICLE_SCHEDULE.TIME3.as("scheduleTime3"),
                        column("parentDept.name").as("parentDeptName"),
                        column("CONCAT(IFNULL(parentDept.name, ''), ' - ', sys_d.name) as fullDeptName"),
                        column("user1.username").as("driverName"),
                        column("user1.phone").as("driverPhone1"),
                        column("user2.username").as("driverName2"),
                        column("user2.phone").as("driverPhone2"),
                        column("user3.username").as("driverName3"),
                        column("user3.phone").as("driverPhone3")
                )
                .from(VEHICLE_INFO.as("vehicle_i"))
                .leftJoin(SYS_DEPT).as("sys_d").on(SYS_DEPT.ID.eq(VEHICLE_INFO.DEPARTMENT_ID))
                .leftJoin(VEHICLE_SCHEDULE).as("vehicle_s").on(VEHICLE_INFO.SCHEDULE_ID.eq(VEHICLE_SCHEDULE.ID))
                .leftJoin(SYS_USER.as("user1")).on("user1.id = vehicle_i.user_id1")
                .leftJoin(SYS_USER.as("user2")).on("user2.id = vehicle_i.user_id2")
                .leftJoin(SYS_USER.as("user3")).on("user3.id = vehicle_i.user_id3")
                .leftJoin(SYS_DEPT.as("parentDept")).on("parentDept.id = sys_d.pid");
        
        // 添加部门ID过滤条件前先检查列表是否为空
        // 检查用户是否为超级管理员(userId=1)或者是否具有role_id=4的角色
        boolean isSuperAdmin = userId == 1;
        boolean hasRole4 = false;
        
        if (!isSuperAdmin) {
            // 检查用户是否具有role_id=4的角色
            try {
                List<String> userRoles = sysUserRoleService.getUserRolesByUserId(userId);
                hasRole4 = userRoles != null && userRoles.contains("4");
            } catch (Exception e) {
                // 如果出现异常，默认不给予特殊权限
                hasRole4 = false;
            }
        }
        
        // 如果用户不是超级管理员且不具有role_id=4的角色，则需要添加部门过滤条件
        if (!isSuperAdmin && !hasRole4) {
            // 非超级管理员，需要添加部门过滤条件
            if (deptAndChildren != null && !deptAndChildren.isEmpty()) {
                // 只查询所属部门及下级部门的设备
                wrapper.where(VEHICLE_INFO.DEPARTMENT_ID.in(new ArrayList<>(deptAndChildren)));
            } else {
                System.out.println("警告: 用户" + userId + "没有任何部门权限，不查询任何设备");
                // 添加一个永远不满足的条件，确保不查询任何设备
                wrapper.where("1 = 0");
            }
        }
                //.where(VEHICLE_INFO.ID.eq(id));
        // 打印SQL用于调试
        System.out.println("Generated SQL: " + wrapper.toSQL());
        if (Utils.isNotNull(dto.getVehicleNumber())) {
            wrapper.eq(VehicleInfo::getVehicleNumber, dto.getVehicleNumber());
        }
        if (Utils.isNotNull(dto.getTitle())) {
            wrapper.eq(VehicleInfo::getTitle, dto.getTitle());
        }
        if (Utils.isNotNull(dto.getSort())) {
            wrapper.eq(VehicleInfo::getSort, dto.getSort());
        }
        if (Utils.isNotNull(dto.getVehicleTypeCd())) {
            wrapper.eq(VehicleInfo::getVehicleTypeCd, dto.getVehicleTypeCd());
        }
        if (Utils.isNotNull(dto.getIsHidden())) {
            wrapper.eq(VehicleInfo::getIsHidden, dto.getIsHidden());
        }
        if (Utils.isNotNull(dto.getDepartmentId())) {
            wrapper.eq(VehicleInfo::getDepartmentId, dto.getDepartmentId());
        }
        return wrapper;
    }
    /**
     *
     */
    /*@Override
    public VehicleInfoVO getVehicleWithDeptById(Long id){
        //VehicleInfo vehicleInfo = getById((Serializable) id);
        List<VehicleInfoVO> vehicleInfoVOList = vehicleInfoMapper.selectListWithRelationsByQueryAs(QueryWrapper.create(), VehicleInfoVO.class);
        //System.out.println(JSON.toJSONString(vehicleInfoVOList));
        CommonResponseEnum.INVALID_ID.assertNull(vehicleInfoVOList);
        return BeanCopyUtils.copy(vehicleInfoVOList, VehicleInfoVO.class);
    }*/
    /*@Override
    public VehicleInfoVO getVehicleWithDeptById(Long id){
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(VEHICLE_INFO.DEFAULT_COLUMNS)
                .from(VEHICLE_INFO)
                .where(VEHICLE_INFO.ID.eq(id));
                //.withRelations();
        List<VehicleInfoVO> vehicleInfoVOList = vehicleInfoMapper.selectListWithRelationsByQueryAs(queryWrapper, VehicleInfoVO.class);
        return BeanCopyUtils.copy(vehicleInfoVOList, VehicleInfoVO.class);
    }*/
    @Override
    public VehicleInfoVO getVehicleWithDeptById(Long id){
        // 定义表别名
        TableDef parentDept = SYS_DEPT.as("parentDept");

        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(VEHICLE_INFO.ALL_COLUMNS, SYS_DEPT.ALL_COLUMNS,
                        SYS_DEPT.NAME.as("deptName"),
                        SYS_DEPT.PID.as("deptPid"),
                        //parentDept.NAME.as("parentDeptName")
                        //DSL.column("parentDept.name").as("parentDeptName")
                        column("parentDept.name").as("parentDeptName"),
                        column("CONCAT(IFNULL(parentDept.name, ''), ' - ', sys_d.name) as fullDeptName")
                )
                .from(VEHICLE_INFO.as("vehicle_i"))
                .leftJoin(SYS_DEPT).as("sys_d").on(SYS_DEPT.ID.eq(VEHICLE_INFO.DEPARTMENT_ID))
                .leftJoin(SYS_DEPT.as("parentDept")).on("parentDept.id = sys_d.pid")
                .where(VEHICLE_INFO.ID.eq(id));
        //.withRelations();
        //List<VehicleInfoVO> vehicleInfoVOList = vehicleInfoMapper.selectListWithRelationsByQueryAs(queryWrapper, VehicleInfoVO.class);
        List<VehicleInfoVO> vehicleInfoVOList = vehicleInfoMapper.selectListByQueryAs(queryWrapper, VehicleInfoVO.class);
        //return BeanCopyUtils.copy(vehicleInfoVOList, VehicleInfoVO.class);
        return vehicleInfoVOList.getFirst();

    }
}